import {Button, Col, Form, Input, message, Modal, Pagination, Row, Space, Table, Card, Typography} from "antd";
import {useEffect, useState} from "react";
import 'antd/dist/antd.css';
import request from "umi-request";
import {PlusOutlined, SearchOutlined, ReloadOutlined} from "@ant-design/icons";

const { Title } = Typography;

interface Executor {
    Id: number;
    Name: string;
    Addresses: string;
    Description: string;
}

interface Response {
    Total: number;
    Data: Executor[];
    Error: string;
}

const ExecutorsPage = () => {
    const [modalTitle, setModalTitle] = useState("新增执行器");
    const columns = [
        {
            title: "序号",
            dataIndex: "Id",
            key: "Id",
        },
        {
            title: "执行器名称",
            dataIndex: "Name",
            key: "Name",
        },
        {
            title: "执行器地址",
            dataIndex: "Addresses",
            key: "Addresses",
        },
        {
            title: "执行器简介",
            dataIndex: "Description",
            key: "Description",
        },
        {
            title: "操作",
            key: "action",
            render: (_: any, record: any) => (
                <Space size="middle">
                    <Button
                        type="primary"
                        onClick={(e) => {
                            updateButtonClickHandler(record);
                        }}
                    >
                        编辑
                    </Button>
                    <Button
                        type="primary"
                        onClick={(e) => {
                            deleteButtonClickHandler(record.Id);
                        }}
                    >
                        删除
                    </Button>
                </Space>
            ),
        },
    ];

    const [isModalVisible, setIsModalVisible] = useState(false);

    const updateButtonClickHandler = (record: any) => {
        setIsModalVisible(true);
        setModalTitle("编辑执行器");
        form.setFieldsValue(record);
    };

    const deleteButtonClickHandler = (id: number) => {
        request
            .post("/api/executor/delete", {
                data: {Id: id},
            })
            .then((res) => {
                message.success(res);
                queryData();
            })
            .catch((error) => {
                message.error("请求数据错误！").then((r) => {
                    console.log(r);
                });
            });
    };
    let inputValue = "";
    const [tasks, setTasks] = useState<Executor[]>([]);

    const [name, setName] = useState<string>("");

    const [pageNo, setPageNo] = useState<number>(1);

    const [pageSize, setPageSize] = useState<number>(10);

    const [total, setTotal] = useState<number>(0);

    const pageChangeHandler = (n: number, size: number) => {
        setPageNo(n);
        setPageSize(size);
    };

    const queryData = () => {
        request
            .post("/api/executor/list", {
                data: {executorName: name, pageNo: pageNo, pageSize: pageSize},
            })
            .then((res) => {
                setTasks(res.Data);
                setTotal(res.Total);
            })
            .catch((error) => {
                message.error("请求数据错误！").then((r) => {
                    console.log(r);
                });
            });
    };
    const handleOk = () => {
        form.submit();
        setIsModalVisible(false);
    };

    const handleCancel = () => {
        setIsModalVisible(false);
        form.resetFields();
    };

    const onFinish = (values: any) => {
        const {Id} = values;
        if (Id) {
            // 更新执行器
            request
                .post("/api/executor/update", {
                    data: values,
                })
                .then((res) => {
                    message.success(res);
                    queryData();
                })
                .catch((error) => {
                    message.error("更新执行器出错！").then((r) => {
                        console.log(error);
                    });
                });
        } else {
            // 新建执行器
            request
                .post("/api/executor/add", {
                    data: values,
                })
                .then((res) => {
                    message.success(res);
                    queryData();
                })
                .catch((error) => {
                    message.error("新建执行器出错！").then((r) => {
                        console.log(error);
                    });
                });
        }
    };

    const layout = {
        labelCol: {span: 8},
        wrapperCol: {span: 16},
    };

    const [form] = Form.useForm();

    useEffect(() => {
        queryData();
    }, [name, pageNo, pageSize]);
    return (
        <div>
            <Card 
                title={<Title level={4}>执行器管理</Title>}
                extra={<Button 
                    type="primary" 
                    icon={<PlusOutlined/>}
                    onClick={() => {
                        setIsModalVisible(true);
                        form.resetFields();
                    }}
                >
                    新增执行器
                </Button>}
                style={{ marginBottom: '24px', borderRadius: '8px' }}
            >
                <Form layout="inline" style={{ marginBottom: '24px' }}>
                    <Form.Item>
                        <Input
                            placeholder="请输入执行器名称"
                            allowClear
                            style={{ width: '240px' }}
                            onChange={(e) => {
                                inputValue = e.target.value;
                            }}
                        />
                    </Form.Item>
                    <Form.Item>
                        <Button
                            type="primary"
                            icon={<SearchOutlined/>}
                            onClick={() => {
                                setName(inputValue);
                                setPageNo(1);
                                queryData();
                            }}
                        >
                            搜索
                        </Button>
                    </Form.Item>
                    <Form.Item>
                        <Button
                            icon={<ReloadOutlined/>}
                            onClick={() => {
                                setName("");
                                setPageNo(1);
                                queryData();
                            }}
                        >
                            重置
                        </Button>
                    </Form.Item>
                </Form>
                
                <Table 
                    columns={columns} 
                    dataSource={tasks} 
                    pagination={false}
                    rowKey="Id"
                    bordered
                    size="middle"
                    style={{ marginBottom: '16px' }}
                />
                
                <Pagination
                    total={total}
                    current={pageNo}
                    pageSize={pageSize}
                    onChange={pageChangeHandler}
                    showSizeChanger
                    showQuickJumper
                    showTotal={(total) => `共 ${total} 条记录`}
                    style={{ textAlign: 'right' }}
                />
            </Card>
            <Modal
                title={modalTitle}
                visible={isModalVisible}
                onOk={handleOk}
                onCancel={handleCancel}
                okText={"确认提交"}
                cancelText={"取消"}
            >
                <Form {...layout} form={form} name="control-hooks" onFinish={onFinish}>
                    <Form.Item name="Id" label="唯一标识" hidden>
                        <Input/>
                    </Form.Item>
                    <Form.Item
                        name="Name"
                        label="执行器名称"
                        rules={[{required: true}]}
                    >
                        <Input/>
                    </Form.Item>
                    <Form.Item
                        name="Addresses"
                        label="执行器地址"
                        rules={[{required: true}]}
                    >
                        <Input/>
                    </Form.Item>
                    <Form.Item name="Description" label="执行器简介">
                        <Input/>
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    );
};

export default ExecutorsPage;
